<?php
namespace sess;
use pdodb;
use SessionHandler;
class session_mysql extends SessionHandler{
    //初始化
    public function __construct(){
    	$this->db=\hc\pdodb::getinstance();
		if(!$this->db){
			msg_error('数据库连接失败');
		}
		$this->db->table(C('session.table'));
	}

    /**
     * 打开Session
     * @access public
     * @param string $savePath
     * @param mixed $sessName
     */
    public function open($savePath, $sessName)
    {
		if (!$this->db){
			return false;
		}
		return true;

    }

    /**
     * 关闭Session
     * @access public
     */
    public function close()
    {
        $this->gc(C('cookie.expire'));
        return true;
    }

    /**
     * 读取Session
     * @access public
     * @param string $sessID
     */
    public function read($session_id)
    {

    	$where['id']=array('=',$session_id);
		if (C('session.ip_address')){
			$where['ip_address']=array('=',getip());
		}

		$result=$this->db->where($where)->select_one();
    	if($result){
    		if($result['timestamp']<time()){//判断是否过期
				$this->destroy($session_id);
				return '';
			}
			return $result['data'];
		}else{
			return '';
		}
    }

    /**
     * 写入Session
     * @access public
     * @param string $sessID
     * @param String $sessData
     */
    public function write($session_id,$session_data)
    {

    	$data['id']=$session_id;
    	$where['id']=array('=',$session_id);
		if (C('session.ip_address')){
			$where['ip_address']=array('=',getip());
		}
		$result=$this->db->where($where)->select_one();
		if($result){
			if($result['data']!=$session_data){
				//通过判断session是否有改变来判断是否更新 或者 根据当前时间是否大于session 保存时间
				$data['timestamp']=time()+C('cookie.expire');
    			$data['data']=$session_data;
    			$this->db->where($where)->update_one($data);
			}

		}else{
			if(!empty($session_data)){
				$data['id']=$session_id;
    			$data['ip_address']=getip();
    			$data['timestamp']=time()+C('cookie.expire');
    			$data['data']=$session_data;
    			$this->db->insert_one($data);
			}

		}
    	return true;
    }

    /**
     * 删除Session
     * @access public
     * @param string $sessID
     */
    public function destroy($session_id)
    {
    	$where['id']=array('=',$session_id);
		if (C('session.ip_address')){
			$where['ip_address']=array('=',getip());
		}
		if($this->db->where($where)->delete_one()){
			return true;
		}else{
			return false;
		}
    }

    /**
     * Session 垃圾回收
     * @access public
     * @param string $sessMaxLifeTime
     */
    public function gc($sessMaxLifeTime)
    {
    	$where['timestamp']=array('<',time());
    	if($this->db->where($where)->delete_one()){
			return true;
		}else{

			return false;
		}

    }

}
